package com.example.sys.job.listener;

import com.example.core.utils.SpringBeanUtils;
import com.example.sys.job.po.SysJobLog;
import com.example.sys.job.service.SysJobLogService;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import static com.example.sys.job.service.SysJobService.JOBID;

public class SysJobLogJobListener implements JobListener {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String JOB_LOG_ID = "JOB_LOG_ID";

    private SysJobLogService sysJobLogService;

    @Override
    public String getName() {
        return getClass().getSimpleName();
    }


    public SysJobLogService getSysJobLogService() {
        if (sysJobLogService == null) {
            sysJobLogService = (SysJobLogService) SpringBeanUtils.getBean(SysJobLogService.class);
        }
        return sysJobLogService;
    }

    /****
     *
     * 任务即将被执行
     * @param jobExecutionContext
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String jobId = jobDataMap.getString(JOBID);
        SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setStartTime(new Date());
        sysJobLog.setJobId(jobId);
        getSysJobLogService().save(sysJobLog);
        jobExecutionContext.put(JOB_LOG_ID, sysJobLog);
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {

    }

    /***
     *
     * 任务执行后调用
     * @param jobExecutionContext
     * @param ex
     */
    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException ex) {
        SysJobLog sysJobLog = (SysJobLog) jobExecutionContext.get(JOB_LOG_ID);
        sysJobLog.setEndTime(new Date());
        if (ex != null) {
            sysJobLog.setEnabled(false);
            sysJobLog.setError(ex.getMessage());
        }
        getSysJobLogService().saveOrUpdate(sysJobLog);
    }
}
